package cn.wolfcode.crm.web.controller;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.StockOutcomeBill;
import cn.wolfcode.crm.query.StockOutcomeBillQueryObject;
import cn.wolfcode.crm.service.IMemberService;
import cn.wolfcode.crm.service.IStockOutcomeBillService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import cn.wolfcode.crm.util.SaleBillSnUtil;

@Controller
@RequestMapping("stockOutcomeBill")
public class StockOutcomeBillController {

    @Autowired
    private IStockOutcomeBillService service;


   /* @Autowired
    private IDepotService depotService;*/
    @Autowired
    private IMemberService memberService;


    @RequestMapping("")
    public String index() {
        return "stockOutcomeBill/list";
    }

    @RequestMapping("list")
    @ResponseBody
    public PageResult list(StockOutcomeBillQueryObject qo) {
        return service.query(qo);
    }



    @RequestMapping("save")
    @ResponseBody
    public JsonResult save(StockOutcomeBill stockOutcomeBill) {
        JsonResult jsonResult = new JsonResult();

        try {
            //1.设置录入时间,当前时间
            Date inputTime = new Date();
            stockOutcomeBill.setInputTime(inputTime);

            //设置录入人,当前登录的用户
           Employee operator = (Employee) SecurityUtils.getSubject().getPrincipal();
           stockOutcomeBill.setOperator(operator);

            //小票默认状态,字段中默认1.
            //小票编码,sn, 根据规则生成
           stockOutcomeBill.setSn(SaleBillSnUtil.getSn());

            //保存小票
            service.insert(stockOutcomeBill);
            //明细在service实现类保存
            
        

        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.markMsg("操作失败!");
        }
        return jsonResult;
    }


    //根据小票单号查小票明细
    @RequiresPermissions("stockOutcomeBill:billItem")
    @PermissionName("小票明细查询")
    @RequestMapping("billItem")
    @ResponseBody
    public PageResult billItem(Long billId) {
        return service.queryBillItemByBillId(billId);
    }

    //根据小票id和商品id执行退货(只有小票id为整单退货,两个参数为部分退货)
    @RequiresPermissions("stockOutcomeBill:saleReturn")
    @PermissionName("小票退货")
    @RequestMapping("saleReturn")
    @ResponseBody
    public JsonResult saleReturn(Long billId,Long itemId){
        JsonResult result = new JsonResult();
        try {
            service.saleReturn(billId,itemId);
        } catch (Exception e) {
            e.printStackTrace();
            result.markMsg("退货失败,请重试!");
        }
        return result;
    }


}
